package person.learn.websocket;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

import java.security.Principal;

/**
 * Created by barton on 16-5-19.
 */
@Controller
public class WsController {

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @MessageMapping("/welcome")
    @SendTo("/topic/getResponse") // 发送给哪一个URL(js中stompClient.subscribe("/topic/getResponse",....)
    public ResponseMessage say(RequestMessage requestMessage) throws InterruptedException {
        Thread.sleep(3000);
        return new ResponseMessage("Welcome, " + requestMessage.getName());
    }

    @MessageMapping("/chat")
    public void handleChat(Principal principal, String msg) {
        System.out.println("================================================" + msg);
        if (principal.getName().equals("barton")) {
            messagingTemplate.convertAndSendToUser("wjj", "/queue/notifications", principal.getName
                    () + "-send: " + msg);
        } else {
            messagingTemplate.convertAndSendToUser("barton", "/queue/notifications", principal
                    .getName() + "-send: " + msg);
        }
    }
}
